package hr.fer.zemris.gep;

public class KarvaEvaluator {
	public Object evaluate(INode[] nodes) {
		NodeEvaluation root = new NodeEvaluation();
		
		root.node = nodes[0];
		processLevel(new NodeEvaluation[] {root}, nodes, 1);
		return root.evaluate();
	}
	
	public String print(INode[] nodes) {
		NodeEvaluation root = new NodeEvaluation();
		
		root.node = nodes[0];
		processLevel(new NodeEvaluation[] {root}, nodes, 1);
		return root.node.print(root.nodeEvals);
	}

	public int length(INode[] nodes) {
		NodeEvaluation root = new NodeEvaluation();
		
		root.node = nodes[0];
		processLevel(new NodeEvaluation[] {root}, nodes, 1);
		int length = getLength(root);
		return length;
	}
	
	private int getLength(NodeEvaluation e) {
		return 0;
	}

	private void processLevel(NodeEvaluation parent[], INode[] nodes, int currentNode) {
		int length = 0;
		
		for (NodeEvaluation n : parent) {
			length += n.node.getAirity();
		}
		
		if (length == 0) {
			return;
		}
		
		NodeEvaluation nodeEvals[] = new NodeEvaluation[length];

		int currentNodeEval = 0;
		for (NodeEvaluation n : parent) {
			NodeEvaluation children[] = new NodeEvaluation[n.node.getAirity()];
			for (int i=0; i<children.length; i++) {
				NodeEvaluation nodeEval = new NodeEvaluation();
				nodeEval.node = nodes[currentNode++];
				nodeEvals[currentNodeEval++] = nodeEval;
				children[i] = nodeEval;
			}
			n.nodeEvals = children;
		}
		
		processLevel(nodeEvals, nodes, currentNode);
	}

	public String print(GEPIndividual ind) {
		StringBuffer buf = new StringBuffer();
		for (int i=0; i<ind.getGeneCount(); i++) {
			buf.append(String.format("\n\n***** Gene %d *****\n\n", i));
			buf.append(print(ind.getGene(i)));
		}
		return buf.toString();
	}
}
